﻿using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;
using System.Threading;    

public abstract class Singleton<T> where T : new() {
    private static T _instance;
    private static object _lock = new object();

    public static T Instance {
        get {
            if (_instance == null) {
                object lockObj = Singleton<T>._lock;
                try
                {
                    if (_instance == null) {
                        _instance = Activator.CreateInstance<T>(); // 需要导入 using System;
                    }
           
                }
                finally {
                    Monitor.Exit(lockObj); // 需要导入 System.Threading;
                }
            }

            return _instance;
        }
    }

    public virtual void Init() {

    }
}

public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T> {
    private static T _instance;
    private static object _lock = new object();

    public static T Instance
    {
        get
        {
            if (_instance == null)
            {
                object obj = MonoSingleton<T>._lock;
                Monitor.Enter(obj);
                _instance = GameObject.FindObjectOfType((typeof(T))) as T;
                if (_instance == null) {
                    _instance = new GameObject(typeof(T).Name, typeof(T)).GetComponent<T>();
                }
                Monitor.Exit(obj);
            }

            return _instance;
        }
    }

    public virtual void SetDontDestroyOnLoad(Transform parent)
    {
        transform.parent = parent;
    }
}
